const URL = require('url');
const express = require('express');
const router = express.Router();
const query=require('../public/javascripts/query');

let sql='';
// 登录接口
router.post('/', function(req, res, next){
  let data=req.body;
  let username = data.username,
    password= data.password;
  sql="select * from userinfo where username = '"+username+"'";
  // console.log(sql);
  query(sql,function(err,rows){
    if(err){
      console.log("err: "+err);
      res.send({code:0});
    }else {
      console.log(rows[0]);
      if(rows.length){
        if(rows[0].password===password){
          res.json({ret_code: 1, ret_msg: '登录成功'});
          req.session.username=username;
          req.session.password=password;
        }else{
          res.json({ret_code: 0, ret_msg: '账号或密码错误'});
        }
      }else{
        return res.json({ret_code: 0, ret_msg: '账号或密码错误'});
      }
    }
  });

});

// 退出登录
router.get('/logout', function(req, res, next){

  req.session.destroy(function(err) {
    if(err){
      res.json({ret_code: 2, ret_msg: '退出登录失败'});
      return;
    }

    res.send('');
  });
});


module.exports = router;
